package leetcode.Over_Four_hundred;
// todo failed
public class Test450删除二叉搜索树中的节点 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return root;
        }
        if (key < root.val) {
            deleteNode(root.left, key);
        } else if (key > root.val) {
            deleteNode(root.right, key);
        } else {

            if (root.left == null && root.right == null) {
                root = null;
            }

            if (root.left == null && root.right != null) {
                root.val = root.right.val;
                root.right = null;
            }

            if (root.left != null && root.right == null) {
                root.val = root.left.val;
                root.left = null;
            }

            if (root.left != null && root.right != null) {
                root.val = root.left.val;
                // 处理 root.left
                del(root.left);
            }
        }
        return root;
    }

    public void del(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        if (treeNode.left != null) {
            treeNode.val = treeNode.left.val;
            del(treeNode.left);
        } else {
            treeNode = null;
        }
    }
}
